import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';

class FMNetMonitorManager {

  static final FMNetMonitorManager _instance = FMNetMonitorManager._internal();

  factory FMNetMonitorManager() => _instance;

  FMNetMonitorManager._internal();

  bool _connectionStatus = false;

  final StreamController<bool> _connectionStatusController =
  StreamController<bool>.broadcast();

  late StreamSubscription<ConnectivityResult> _subscription;

  bool get connectionStatus => _connectionStatus;

  void init() {
    _checkCurrentConnection();

    _subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      _updateConnectionStatus(result);
    });
  }

  Future<void> _checkCurrentConnection() async {
    final result = await Connectivity().checkConnectivity();
    _updateConnectionStatus(result);
  }

  void _updateConnectionStatus(ConnectivityResult result) {
    if (result == ConnectivityResult.none) {
      _connectionStatus = false;
    } else {
      _connectionStatus = true;
    }
    _connectionStatusController.add(_connectionStatus);
  }

  Stream<bool> get connectionStatusStream => _connectionStatusController.stream;

  void dispose() {
    _subscription.cancel();
    _connectionStatusController.close();
  }

}